package com.hlkj.pay.config;

import cn.hutool.core.collection.CollUtil;
import com.hlkj.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.hlkj.pay.infrastructure.mapper.merchant.MerchantAccessAuthMapper;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessAuthDO;
import com.hlkj.pay.util.OrderCodeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 应用启动后执行代码的方法，通常用于数据库迁移、初始化数据等操作
 */
@Component
@RequiredArgsConstructor
public class StartupRunner implements CommandLineRunner {

    private final MerchantAccessAuthMapper merchantAccessAuthMapper;

    private final OrderCodeUtil orderCodeUtil;

    @Override
    public void run(String... args) throws Exception {
        // 仅在应用启动时执行一次的代码
        System.out.println("应用启动时执行的代码");
        // 更新AUT code
        LambdaQueryWrapperX<MerchantAccessAuthDO> queryWrapper = new LambdaQueryWrapperX<>();
        queryWrapper.isNull(MerchantAccessAuthDO::getCode);
        List<MerchantAccessAuthDO> merchantAccessAuthList = merchantAccessAuthMapper.selectList(queryWrapper);
        if(CollUtil.isNotEmpty(merchantAccessAuthList)){
            List<MerchantAccessAuthDO> updateList = new ArrayList<>();
            MerchantAccessAuthDO auth = null;
            for(MerchantAccessAuthDO authDO:merchantAccessAuthList){
                auth = new MerchantAccessAuthDO();
                auth.setId(authDO.getId());
                auth.setCode(orderCodeUtil.orderNo("AUT",8));
                updateList.add(auth);
            }
            merchantAccessAuthMapper.updateBatch(updateList,updateList.size());
        }

    }
}